package com.leetcode.题库;

import com.leetcode.common.model.ListNode;

/**
 * @author 覃国强
 * @date 2022-02-19 19:38
 */
public class 题库_0002_两数相加 {


  static
  class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      if (l1 == null || l2 == null) {
        return l1 != null ? l1 : l2;
      }

      ListNode result = new ListNode();
      ListNode curNode = result;
      int carry = 0;

      while (l1 != null && l2 != null) {
        int temp = carry + l1.val + l2.val;
        carry = temp > 9 ? 1 : 0;
        curNode.next = new ListNode();
        curNode = curNode.next;
        curNode.val = temp % 10;
        l1 = l1.next;
        l2 = l2.next;
      }

      while (l1 != null) {
        int temp = carry + l1.val;
        carry = temp > 9 ? 1 : 0;
        curNode.next = new ListNode();
        curNode = curNode.next;
        curNode.val = temp % 10;
        l1 = l1.next;
      }

      while (l2 != null) {
        int temp = carry + l2.val;
        carry = temp > 9 ? 1 : 0;
        curNode.next = new ListNode();
        curNode = curNode.next;
        curNode.val = temp % 10;
        l2 = l2.next;
      }

      if (carry > 0) {
        curNode.next = new ListNode();
        curNode = curNode.next;
        curNode.val = 1;
      }

      return result.next;
    }

  }

}
